import os, sys

import logging
from concurrent_log_handler import ConcurrentRotatingFileHandler
import psutil
from enum import Enum
from manual_config import Manual_config
# class log_config():
#     TRACE = 1
#     LOG_LEVEL = "INFO"
#     DEBUG = 1

class LogLevle(Enum):
    DEBUG = 10
    INFO = 20
    WARN = 30
    ERROR = 40
    FALAL = 50




class LogHelper(object):

    def __init__(self,tag,filepath = None,filename = None):
        self.localpid = os.getpid()
        proce = psutil.Process(pid=self.localpid)
        localpidcmdline =  proce.cmdline()
        print (localpidcmdline)

        lfilename = filename
        if not lfilename:
            lfilename = "_".join(map(lambda x:str(x),localpidcmdline))
            print (lfilename)
            lfilename = lfilename.replace('.','_')
            lfilename = lfilename.replace('/','_')
            lfilename = lfilename.replace('\\','_')
            lfilename = lfilename + ".log"

        lfilepath = filepath            
        if not lfilepath:
            #获取用户主目录
            # usr_home = os.path.expanduser('~')
            # lfilepath = os.path.join(usr_home,"logs/py_logs")
            # lfilepath = "/opt/logs/alert_log"
            #获取用户当前工作目录
            usr_work_home = os.getcwd()
            lfilepath = os.path.join(usr_work_home,"py_logs")
        self.log_path = lfilepath
        if not os.path.exists(self.log_path):
            print("mkdir", self.log_path)
            os.makedirs(self.log_path)
        logging.basicConfig(level=logging.INFO)
        # logging.basicConfig(level=10)
        self.tag = tag

#建立日志接口
        self.logger = logging.getLogger(self.tag)  
        self.logger.setLevel(logging.INFO)
        # self.logger.setLevel(10)
        self.logger.propagate = False

        if not self.logger.handlers:
            ch = logging.StreamHandler()
            self.logger.addHandler(ch)

            if len(lfilename) > 100:
                lfilename = lfilename[-32:]
            llfilename = os.path.join(self.log_path, lfilename)
            # fh = logging.handlers.TimedRotatingFileHandler(os.path.join(self.path, tag), when="midnight", interval=1, backupCount=0)
            fh = ConcurrentRotatingFileHandler(llfilename, maxBytes=1024 * 1024 * 5, backupCount=3,
                                               delay=0)

            formatter = logging.Formatter('%(asctime)s ||| %(name)s ||| %(message)s')

            fh.setLevel(logging.INFO)
            fh.setFormatter(formatter)
            self.logger.addHandler(fh)

    def log_debug(self, transaction_id='transaction_id', user='user', msg_info='msg_info', value='##value##',
                        location_code = "location_code_default"):
        if LogLevle.DEBUG.value >= LogLevle[getattr(Manual_config,"LOG_LEVEL","INFO")].value:
            level = "DEBUG"
            massage = "{} ||| {} ||| {} ||| {} ||| {} ||| {} ||| {}".format(level, transaction_id, user, 
                                                                    location_code,self.localpid,msg_info,value)
            self.logger.info(massage)

    def log_info(self, transaction_id='transaction_id', user='user', msg_info='msg_info', value='##value##',
                        location_code = "location_code_default"):
        if LogLevle.INFO.value >= LogLevle[getattr(Manual_config,"LOG_LEVEL","INFO")].value:        
            level = "INFO"
            massage = "{} ||| {} ||| {} ||| {} ||| {} ||| {} ||| {}".format(level, transaction_id, user, 
                                                                    location_code,self.localpid,msg_info,value)
            self.logger.info(massage)
    def log_warning(self, transaction_id='transaction_id', user='user',  msg_info='msg_info', value='##value##',
                        location_code = "location_code_default"):
        if LogLevle.WARN.value >= LogLevle[getattr(Manual_config,"LOG_LEVEL","INFO")].value:        
            level = "WARN"
            massage = "{} ||| {} ||| {} ||| {} ||| {} ||| {} ||| {}".format(level, transaction_id, user, 
                                                                    location_code,self.localpid,msg_info,value)
            self.logger.warning(massage)

    def log_error(self, transaction_id='transaction_id', user='user', msg_info='msg_info', value='##value##',
                        location_code = "location_code_default"):
        level = "ERROR"
        massage = "{} ||| {} ||| {} ||| {} ||| {} ||| {} ||| {}".format(level, transaction_id, user, 
                                                                    location_code,self.localpid,msg_info,value)
        self.logger.error(massage,exc_info=True,stack_info=True)


    def log_exception(self, transaction_id='transaction_id', user='user', msg_info='msg_info', value='##value##',
                        location_code = "location_code_default"):
        level = "ERROR"
        massage = "{} ||| {} ||| {} ||| {} ||| {} ||| {} ||| {}".format(level, transaction_id, user, 
                                                                    location_code,self.localpid,msg_info,value)
        self.logger.exception(massage,exc_info=True,stack_info=True)


    def log_critical(self, transaction_id='transaction_id', user='user', msg_info='msg_info', value='##value##',
                        location_code = "location_code_default"):
        level = "FALAL"
        massage = "{} ||| {} ||| {} ||| {} ||| {} ||| {} ||| {}".format(level, transaction_id, user, 
                                                                    location_code,self.localpid,msg_info,value)
        self.logger.critical(massage,exc_info=True,stack_info=True)


    def log(self, level,transaction_id='transaction_id', user='user', msg_info='', value='',
                        location_code = "location_code_default"):
        '''
        :param transaction_id: 事务号
        :param user: 机器号
        :param msg_info: 日志类型 日志说明 exp "收到请求"
        :param value: 日志详情
        :param log_level: 记入等级标杆，低于此标杆对日志不计
        :param level: 日志级别　{"DEBUG":10,"INFO":20,"WARN":30,"ERROR":40,"FALAL":50}
        :return:
        '''
        if LogLevle[level].value >= LogLevle[getattr(Manual_config,"LOG_LEVEL","INFO")].value: 
            massage = "{} ||| {} ||| {} ||| {} ||| {} ||| {} ||| {}".format(level, transaction_id, user, 
                                                                    location_code,self.localpid,msg_info,value)
            self.logger.info(massage)



class TraceHelper(object):

    def __init__(self,tag,filepath = None,filename = None):
        self.localpid = os.getpid()
        proce = psutil.Process(pid=self.localpid)
        localpidcmdline =  proce.cmdline()
        print (localpidcmdline)

        lfilename = filename
        if not lfilename:
            lfilename = "_".join(map(lambda x:str(x),localpidcmdline))
            print (lfilename)
            lfilename = lfilename.replace('.','_')
            lfilename = lfilename.replace('/','_')
            lfilename = lfilename.replace('\\','_')
            lfilename = lfilename + ".csv"

        lfilepath = filepath            
        if not lfilepath:
            #获取用户主目录
            # usr_home = os.path.expanduser('~')
            # lfilepath = os.path.join(usr_home,"logs/trace_logs")
            # lfilepath = "/opt/logs/trace_logs"
            #获取用户当前工作目录
            usr_work_home = os.getcwd()
            lfilepath = os.path.join(usr_work_home,"trace_logs")
        
        self.log_path = lfilepath
        if not os.path.exists(self.log_path):
            print("mkdir", self.log_path)
            os.makedirs(self.log_path)
        logging.basicConfig(level=logging.INFO)
        # logging.basicConfig(level=10)
        self.tag = tag + "_trace"

#建立日志接口
        self.logger = logging.getLogger(self.tag)  
        self.logger.setLevel(logging.INFO)
        # self.logger.setLevel(10)
        self.logger.propagate = False

        if not self.logger.handlers:
            # ch = logging.StreamHandler()
            # self.logger.addHandler(ch)
            # fh = logging.handlers.TimedRotatingFileHandler(os.path.join(self.path, tag), when="midnight", interval=1, backupCount=0)
            # if len(lfilename) > 100:
            #     lfilename = lfilename[-100:-1]
            # llfilename = os.path.join(self.log_path, lfilename)
            if len(lfilename) > 100:
                lfilename = lfilename[-100:]
            llfilename = os.path.join(self.log_path, lfilename)
            # fh = logging.handlers.TimedRotatingFileHandler(os.path.join(self.path, tag), when="midnight", interval=1, backupCount=0)
            fh = ConcurrentRotatingFileHandler(llfilename, maxBytes=1024 * 1024 * 5, backupCount=3,
                                               delay=0)

            formatter = logging.Formatter('%(asctime)s  |  %(name)s  |  %(message)s')

            fh.setLevel(logging.INFO)
            fh.setFormatter(formatter)
            self.logger.addHandler(fh)


    def log(self,transaction_id='transaction_id', start_time='start_time', end_time='end_time', run_time='run_time',
                        in_parameter = "in_parameter",out_parameter = "out_parameter"):
        '''
        :param opposite: 对应的模块
        :param transaction_id: 事务号
        :param user: 机器号
        :param msg_info: 日志类型 日志说明 exp _request request response _response
        :param value: 日志详情
        :return:
        '''
        # print("*****************")
        # in_parameter = in_parameter.replace('|', '/')
        # out_parameter = out_parameter.replace('|', '/')
        if getattr(Manual_config,"TRACE",False): 
            massage = "{}  |  {}  |  {}  |  {}  |  {}  |  {}".format(transaction_id, start_time, 
                                                                    end_time,run_time,in_parameter,out_parameter)
            self.logger.info(massage)



class DebugHelper(object):

    def __init__(self,tag,filepath = None,filename = None):
        self.localpid = os.getpid()
        proce = psutil.Process(pid=self.localpid)
        localpidcmdline =  proce.cmdline()
        print (localpidcmdline)

        lfilename = filename
        if not lfilename:
            lfilename = "_".join(map(lambda x:str(x),localpidcmdline))
            print (lfilename)
            lfilename = lfilename.replace('.','_')
            lfilename = lfilename.replace('/','_')
            lfilename = lfilename.replace('\\','_')
            lfilename = lfilename + ".log"

        lfilepath = filepath            
        if not lfilepath:
            #获取用户主目录
            # usr_home = os.path.expanduser('~')
            # lfilepath = os.path.join(usr_home,"logs/debug_logs")
            # lfilepath = "/opt/logs/debug_logs"
            #获取用户当前工作目录
            usr_work_home = os.getcwd()
            lfilepath = os.path.join(usr_work_home,"debug_logs")
        
        self.log_path = lfilepath
        if not os.path.exists(self.log_path):
            print("mkdir", self.log_path)
            os.makedirs(self.log_path)
        logging.basicConfig(level=logging.INFO)
        # logging.basicConfig(level=10)
        self.tag = tag + "_debug"

#建立日志接口
        self.logger = logging.getLogger(self.tag)  
        self.logger.setLevel(logging.INFO)
        # self.logger.setLevel(10)
        self.logger.propagate = False

        if not self.logger.handlers:
            ch = logging.StreamHandler()
            self.logger.addHandler(ch)
            # fh = logging.handlers.TimedRotatingFileHandler(os.path.join(self.path, tag), when="midnight", interval=1, backupCount=0)
            if len(lfilename) > 100:
                lfilename = lfilename[-100:]
            llfilename = os.path.join(self.log_path, lfilename)
            # fh = logging.handlers.TimedRotatingFileHandler(os.path.join(self.path, tag), when="midnight", interval=1, backupCount=0)
            fh = ConcurrentRotatingFileHandler(llfilename, maxBytes=1024 * 1024 * 5, backupCount=3,
                                               delay=0)

            formatter = logging.Formatter('%(asctime)s ||| %(name)s ||| %(message)s')

            fh.setLevel(logging.INFO)
            fh.setFormatter(formatter)
            self.logger.addHandler(fh)


    def log(self,key = "",value='', location_code = "location_code_default"):
        '''
        :param transaction_id: 事务号
        :param user: 机器号
        :param msg_info: 日志类型 日志说明 exp "收到请求"
        :param value: 日志详情
        :param log_level: 记入等级标杆，低于此标杆对日志不计
        :param level: 日志级别　{"DEBUG":10,"INFO":20,"WARN":30,"ERROR":40,"FALAL":50}
        :return:
        '''

        if getattr(Manual_config,"DEBUG",False): 
            massage = "{} ||| {} ||| {} ||| {}".format(location_code,key,value,type(value))
            self.logger.info(massage)



if __name__ == '__main__':
    # script, tag, path = argv
    tag = 'test0001'
    l = LogHelper(tag)
    l.log_info(value = 'abc')
    tag1 = 'test0002'
    l1 = LogHelper(tag1)
    l1.log_error(value = 'abc1')
    l1.log_debug()
    l1.log_info()
    l1.log_warning()
    l1.log_error()
    l1.log_exception()
    l1.log_critical()
    # l.log_debug('abc')
    # l.log_warn('abc')
    # l.log_error('abc')
    l2 = TraceHelper(tag1)
    l3 = DebugHelper(tag)
    l2.log(transaction_id='transaction_id', start_time='start_time', end_time='end_time', run_time='run_time',
                        in_parameter = "in_parameter",out_parameter = "out_parameter")
    l3.log(key = "mon",value='dsagsg', location_code = sys._getframe().f_lineno)

    # while 1:
    #     i = input('input: ')
    #     # l.log_info(i)
    #     l.log("INFO",'transaction_id', 'user','日志说明', i)
